package com.xc.freeapp.util;


import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;

import com.xc.freeapp.exception.BaseException;
import com.xc.freeapp.jwt.JWTExpiredException;
import com.xc.freeapp.jwt.JWTSigner;
import com.xc.freeapp.jwt.JWTVerifier;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by shaowen on 2015/7/13.
 */
public class JwtUtil {

    private static final byte[] secret = new Base64(true).decodeBase64("AyM1S2sPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr4T-1qS0gdH75aKtMN3Yj0iPS4ecgUuTwjAzZr1Z9CAow");

    /**
     * 签名
     * @param deviceId
     * @param userId
     * @return
     */
    public static String sign(String deviceId,Integer userId) {

        HashMap<String, Object> claims = getClamis(deviceId,userId);
        String token = new JWTSigner(secret).sign(claims,new JWTSigner.Options()
                .setExpirySeconds(30*24*60*60).setNotValidBeforeLeeway(10).setIssuedAt(true));
        return token;
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static Map<String, Object> vifity(String token){
        Map<String, Object> decoded = null;
        try {
            decoded = new JWTVerifier(secret).verify(token);
        } catch (SignatureException e) {
            throw new BaseException("","");
        } catch (JWTExpiredException e){
        	throw new BaseException("","");
        }catch (Exception e){
        	throw new BaseException("","");
        }finally {
            return  decoded;
        }
    }

    /**
     * 刷新token
     * @param token
     * @return
     */
    public static String refresh_token(String token) {
        Map<String, Object> decoded =  vifity(token);
        int userId = ((Number) decoded.get("userId")).intValue();
        String deviceId =  decoded.get("deviceId").toString();
        return sign(deviceId,userId);
    }

    /**
     * @param deviceId
     * @param userId
     * @return
     */
    private static HashMap<String, Object> getClamis(String deviceId,Integer userId){
        HashMap<String, Object> claims = new HashMap<String, Object>();
        long date = new Date().getTime();
        claims.put("deviceId",deviceId);
        claims.put("userId",userId);
        claims.put("time",date);
//        if(StringUtil.killEmpty(deviceId)==null||userId==null){
//        	throw new BaseException("","");
//        }
        return claims;
    }
}
